package touche.touche;

import model.GameManager;
import model.GameModel;
import model.GameModelInterface;
import view.GameView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import controller.GameController;
import controller.GameControllerInterface;

public class GameActivity extends Activity {

	GameView _gameAdventureView = null;
	private boolean _hasClosedAlert = false;

	void createMVC() {
		GameManager.getInstance().setActivity(this);
		GameModelInterface model = new GameModel(GameManager.getInstance()
				.getCurrentLevel());
		GameControllerInterface controller = new GameController(model);
		_gameAdventureView = controller.getView();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this._gameAdventureView = null;
		this._hasClosedAlert = false;
		setContentView(R.layout.game);

		// We create the calculator based on MVC design pattern
		createMVC();

		TextView textViewLife = (TextView) findViewById(R.id.textViewLife);
		ProgressBar progressBarLife = (ProgressBar) findViewById(R.id.progressBarLife);

		TextView textViewScore = (TextView) findViewById(R.id.textViewScore);
		TextView textViewTime = (TextView) findViewById(R.id.textViewTime);
		TextView textViewLevel = (TextView) findViewById(R.id.textViewLevel);

		Button buttonPause = (Button) findViewById(R.id.buttonPause);

		GridView gridViewPictures = (GridView) findViewById(R.id.gridViewPictures);

		// We set widgets in the View part of the MVC
		_gameAdventureView.setWidgets(textViewLife, progressBarLife,
				textViewScore, textViewTime, textViewLevel, buttonPause,
				gridViewPictures);

		// We set all listeners on the GUI widgets
		_gameAdventureView.setListeners();

		_gameAdventureView.setActivity(this);
		
		AlertDialog alert = new AlertDialog.Builder(this).create();

		alert.setTitle(GameManager.getInstance().getCurrentLevel()
				.getAlertTitle());

		alert.setMessage(this.getText(GameManager.getInstance()
				.getCurrentLevel().getAlertContent()));

		alert.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				_gameAdventureView.getController().start();
				_hasClosedAlert = true;
			}
		});
		alert.show();
	}

	protected void onPause() {
		super.onPause();
		Log.d("GameActivity", "onPause");
		_gameAdventureView.getController().pause();
	}

	protected void onResume() {
		super.onResume();
		Log.d("GameActivity", "onResume");

		if (_hasClosedAlert) {
			_gameAdventureView.getController().start();
		}
	}
}